<template>
  <div>
    <medicalCard title="服务管理">
      <template v-slot:head>
        <template>
          <Button icon="md-add" type="success" class="headFormItemButton" @click="add()">新增</Button>
          <Button icon="md-trash" type="error" class="headFormItemButton" @click="delList">删除</Button>
        </template>
        <vxe-table border="outer" header-align="center" ref="my_table"
                   :loading="loading"
                   :data="tableData"
                   :stripe="true"
                   style="margin-top: 5px;margin-bottom: 10px"
                   :highlight-hover-row="true"
                   :scroll-x="{gt: 0}" align="center" show-overflow="tooltip">
          <vxe-table-column width="60" fixed="left" type="checkbox"></vxe-table-column>
          <vxe-table-column field="give_service_type" fixed="left" title="分类" min-width="200"></vxe-table-column>
          <vxe-table-column field="give_service_name" fixed="left" title="名称" min-width="200"></vxe-table-column>
          <vxe-table-column  title="图片" min-width="200">
            <template v-slot="{ row }">
              <img :src="row.give_service_picture" preview width="40px" height="40px" />
            </template>
          </vxe-table-column>
          <vxe-table-column field="give_service_synopsis" title="简介" min-width="200">
            <template v-slot="{ row }">
              <span>{{row.give_service_synopsis}}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column field="type" title="描述" min-width="200">
            <template v-slot="{ row }">
              <span>{{row.give_service_describe}}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column field="give_service_price" title="建议价格" min-width="200">
            <template v-slot="{ row }">
              <span>¥{{row.give_service_price}}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column field="sort" title="排序" min-width="200">
            <template v-slot="{ row }">
              <Poptip v-model="row.poptipVisible" placement="top" style="z-index: 9999" :transfer='true'>
                <a href="javascript:void(0);" style="color: #2D8cF0;" @click="row.newSort = row.sort">{{row.sort}}</a>
                <template #content>
                  <Input type="text" clearable v-model="row.newSort" class="headFormItemWidth" />
                  <Button type="success"  icon="md-checkmark" style="padding: 0;margin-left: 2px" @click="editSort(row)"></Button>
                  <Button icon="md-close" style="padding: 0;margin-left: 2px" @click="row.poptipVisible = false"></Button>
                </template>
              </Poptip>
            </template>
          </vxe-table-column>
          <vxe-table-column field="state" title="状态" min-width="200">
            <template v-slot="{ row }">
              <i-Switch v-model="row.state" size="large" true-color="#13ce66" false-color="#ff4949" true-value="1" false-value="2" @on-change="editState(row)">
                <template #open>
                  <span>开启</span>
                </template>
                <template #close>
                  <span>关闭</span>
                </template>
              </i-Switch>
            </template>
          </vxe-table-column>
          <vxe-table-column width="200" fixed="right" title="操作">
          <template scp-layout="true" v-slot="{ row }">
            <ButtonGroup>
              <Button type="warning" icon="md-create" style="padding: 0" @click="edit(row)"></Button>
              <Button type="error" icon="md-trash" style="padding: 0" @click="del(row)"></Button>
            </ButtonGroup>
          </template>
          </vxe-table-column>
        </vxe-table>
        <Row type="flex" justify="end">
          <Page :current="params.pageNo" :total="params.totalRecord" show-sizer :page-size="params.pageSize" show-elevator
                @on-change="pageAction" @on-page-size-change="pageSizeChange"/>
        </Row>
      </template>
      <template v-slot:body :showFlag="showFlag">
      </template>
    </medicalCard>
    <Modal v-model="modal.show" draggable sticky scrollable :closable="false" :mask="false" :title="modal.title" width="750">
      <Tabs type="card">
        <TabPane label="基础设置">
          <basic-card :formItem="formItem" :tableList="tableList" :tableList1="tableList1"></basic-card>
        </TabPane>
        <TabPane label="图文设置">
          <Image-text-card :formItem="twFormItem"></Image-text-card>
        </TabPane>
      </Tabs>
      <div slot="footer">
        <Button type="default" @click="modal.show=false">取消</Button>
        <Button type="primary" @click="save()">确定</Button>
      </div>
    </Modal>
  </div>

</template>

<script>
import medicalCard from '@/view/medical-page/components/medical-card'
import BasicCard from '../components/service-card/basic-card.vue'
import ImageTextCard from '../components/service-card/image-text-card.vue'

import {
  findGiveList,
  insertGiveService,
  deleteGiveService,
  insertRotationChart,
  updateGiveService,
  getSign,
  createUpLoadFiles
} from '@/api/medical'
export default {
  name: 'hospital-list',
  components: {
    medicalCard,
    BasicCard,
    ImageTextCard
  },
  data () {
    return {
      formItem: {},
      twFormItem: {},
      showFlag: false,
      location: {
        lng: 123.412581,
        lat: 41.805853
      },
      lng: null,
      lat: null,
      map: null,
      marker: null,
      options: [],
      inputSearch: '',
      coordinate: '',
      loading1: false,
      loading: false,
      imgList: [],
      visible: false,
      poptipVisible: false,
      imgListShow: '',
      modal: {
        show: false,
        type: null,
        data: {},
        title: ''
      },
      params: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0
      },
      tableData: [],
      cityList: [
        { label: '沈阳市', value: '210101' }
      ],
      selectList: [],
      positionList: [
        { label: '用户页面', value: '1' },
        { label: '陪诊机构页面', value: '2' },
        { label: '陪诊师页面', value: '3' },
        { label: '广告位', value: '4' }
      ], // 位置
      typeList: [
        { label: '网址', value: '1' },
        { label: '医院', value: '2' },
        { label: '陪诊机构', value: '3' },
        { label: '陪诊师', value: '4' },
        { label: '服务', value: '5' }
      ], // 跳转类别
      tableList: [],
      tableList1: []
    }
  },
  computed: {
  },
  inject: [
    'reload'
  ],
  methods: {
    search () {
      this.params.pageNo = 1
      this.params.totalRecord = 0
      this.init()
    },
    init () {
      this.loading = true
      findGiveList(this.params).then(ret => {
        if (ret.data.errcode === 0) {
          this.tableData = ret.data.data.results
          this.params.totalRecord = ret.data.data.totalRecord
          this.loading = false
        } else {
          this.$Message.error(ret.data.errmsg)
        }
      })
    },
    selectCity (value) {
      this.modal.data.code_name = JSON.parse(value.tag).label
      this.modal.data.city_code = JSON.parse(value.tag).value
    },
    del (row) {
      this.$Modal.confirm({
        title: '<p style="color:#f60;text-align:center">\n' +
          '                    <Icon type="ios-information-circle"></Icon>\n' +
          '                    <span>删除操作</span>\n' +
          '                </p>',
        content: '<p>确定要执行该操作吗？</p>',
        width: 300,
        loading: true,
        onOk: () => {
          let param = {
            giveServiceIds: [
              {
                give_service_id: row.give_service_id
              }
            ]
          }
          deleteGiveService(param).then(ret => {
            if (ret.data.errcode === 0) {
              this.$Message.success({
                content: '操作成功,\n' + ret.data.errmsg
              })
              this.init()
            } else {
              this.$Message.error({
                content: '操作失败,\n' + ret.data.errmsg
              })
            }
          })
          this.$Modal.remove()
        }
      })
    },
    add () {
      // this.initMap(this.location)
      this.modal.data = {}
      this.coordinate = ''
      this.inputSearch = ''
      this.selectList = []
      // this.selectCityList()
      this.modal.title = '新增'
      this.modal.type = 0
      this.modal.show = true
    },
    editSort (row) {
      let params = {
        hospital_id: row.hospital_id,
        sort: row.newSort
      }
      this.updateHospital(params)
    },
    editState (row) {
      let params = {
        give_service_id: row.give_service_id,
        state: row.state
      }
      this.updateState(params)
    },
    edit (row) {
      this.formItem = row
      this.twFormItem = row
      if (row.give_service_label) {
        console.log(row.give_service_label)
        this.formItem.service_label_arr = row.give_service_label.split(',')
        console.log(this.formItem.service_label_arr, '标签')
      }
      if (row.give_service_picture) {
        this.imgList[0] = [row.give_service_picture]
      }
      if (row.give_service_field) {
        this.tableList = JSON.parse(row.give_service_field)
      }
      if (row.hospital_field) {
        this.tableList1 = JSON.parse(row.hospital_field)
        console.log(this.tableList1, '回显医院')
      }
      this.modal.title = '修改'
      this.modal.show = true
    },
    addOk () {
      if (this.imgList.length > 0) {
        this.modal.data.url = this.imgList[0]
      }
      if (!this.modal.data.id) {
        insertRotationChart(this.modal.data).then(ret => {
          if (ret.data.errcode === 0) {
            this.modal.show = false
            this.$Message.success({
              content: '操作成功,\n' + ret.data.errmsg
            })
            this.init()
          } else {
            this.$Message.error({
              content: '操作失败,\n' + ret.data.errmsg
            })
          }
        })
      }
      if (this.modal.type === 1) {
        this.updateHospital(this.modal.data)
      }
    },
    updateState (e) {
      updateGiveService(e).then(ret => {
        if (ret.data.errcode === 0) {
          this.modal.show = false
          this.$Message.success({
            content: '操作成功,\n' + ret.data.errmsg
          })
          this.init()
        } else {
          this.$Message.error({
            content: '操作失败,\n' + ret.data.errmsg
          })
        }
      })
    },
    delList () {
      let selectRecords = this.$refs.my_table.getCheckboxRecords()
      if (!selectRecords || selectRecords.length === 0) {
        this.$Message.error({
          content: '操作失败,\n' + '请选择删除项'
        })
        return
      }
      let array = []
      selectRecords.forEach(element => {
        array.push({ give_service_id: element.give_service_id })
      })
      // let array = selectRecords.map((item) => {give_service_id: item.give_service_id})
      this.$Modal.confirm({
        title: '<p style="color:#f60;text-align:center">\n' +
          '                    <Icon type="ios-information-circle"></Icon>\n' +
          '                    <span>删除操作</span>\n' +
          '                </p>',
        content: '<p>确定要执行该操作吗？</p>',
        width: 300,
        loading: true,
        onOk: () => {
          deleteGiveService({ giveServiceIds: array }).then(ret => {
            if (ret.data.errcode === 0) {
              this.$Message.success({
                content: '操作成功,\n' + ret.data.errmsg
              })
              this.init()
            } else {
              this.$Message.error({
                content: '操作失败,\n' + ret.data.errmsg
              })
            }
          })
          this.$Modal.remove()
        }
      })
    },
    pageAction (page) {
      this.params.pageNo = page
      this.init()
    },
    pageSizeChange (e) {
      this.params.pageSize = e
      this.init()
    },
    handleView (img) {
      this.imgListShow = img
      this.visible = true
    },
    handleRemove (file) {
      this.imgList.splice(this.imgList.indexOf(file), 1)
    },
    handleBeforeUpload (file) {
      // const check = this.imgList.length < 1
      // if (!check) {
      //   this.$Notice.warning({
      //     title: '最多上传1张图片'
      //   })
      //   return check
      // }
      this.beforeUpload(file)
    },
    beforeUpload (file) {
      let upPicData = {}
      // upPicData.filePath = 'medical/hospital/images'
      upPicData.filePath = 'medical/banner/images'
      upPicData.fileName = this.modal.data.hospital_name ? this.modal.data.hospital_name : '轮播图片'
      var time = new Date().getTime()
      let timestamp = time.toString()
      upPicData.timestamp = timestamp
      let that = this
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        let index = reader.result.indexOf('base64,') + 7
        upPicData.fileName = upPicData.fileName + timestamp + '.' + file.type.substring(6)
        upPicData.file = reader.result.substring(index)
        that.upPic(upPicData)
      }
      return false
    },
    upPic (fileData) {
      getSign({
        filePath: fileData.filePath,
        fileName: fileData.fileName,
        timestamp: fileData.timestamp
      }).then(res => {
        if (res.data.errcode === 0) {
          createUpLoadFiles(res.data.data.docking_url, {
            sign: res.data.data.sign,
            timestamp: fileData.timestamp,
            filePath: fileData.filePath,
            fileName: fileData.fileName,
            file: fileData.file
          }).then(ret => {
            if (ret.data.errcode === 0) {
              this.imgList = [ret.data.data]
              this.modal.data.picture = this.imgList[0]
              this.$Message.success({
                content: '上传成功,\n' + ret.data.errmsg
              })
            } else {
              this.$Message.error({
                content: '上传失败,\n' + ret.data.errmsg
              })
            }
          })
        }
      })
    },
    save () { // 添加服务
      this.formItem.give_service_label = this.formItem.service_label_arr.reduce((prev, curr) => prev + ',' + curr)
      this.formItem.give_service_field = JSON.stringify(this.tableList)
      this.formItem.hospital_field = JSON.stringify(this.tableList1)
      let idArr = []
      this.tableList1.forEach(element => {
        idArr.push(element.hospital_id)
      })
      this.formItem.hospital_ids = idArr.join(',')
      const param = { ...this.formItem, ...this.twFormItem }
      let url = this.formItem.give_service_id ? updateGiveService : insertGiveService
      url(param).then(res => {
        if (res.data.errcode === 0) {
          this.$Message.success({
            content: '操作成功,\n' + res.data.errmsg
          })
          this.modal.show = false
          this.init()
          this.formItem = {}
          this.twFormItem = {}
          return
        }
        this.$Message.error({
          content: '操作失败,\n' + res.data.errmsg
        })
      })
    }
  },
  watch: {
  },
  mounted () {
    this.init()
  }
}
</script>
<style scoped>
#mapHospitalAddress {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 500px;
}
.headFormItemWidth{
  width: 200px;
}
.headFormItemButton{
  margin-right: 10px;
}
.formItem{
  float: right;
}
</style>
